from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import Enum, ForeignKey, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship as sa_relationship

from app.db.base_class import BaseEntity

if TYPE_CHECKING:
  from .relationship import Relationship
  from .user import User
  from .diary_comment import DiaryComment


class DiaryEntry(BaseEntity):
  __tablename__ = "diary_entries"

  user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
  relationship_id: Mapped[int | None] = mapped_column(ForeignKey("relationships.id"), index=True)
  title: Mapped[str | None] = mapped_column(String(180), nullable=True)
  content_md: Mapped[str] = mapped_column(Text)
  mood: Mapped[str | None] = mapped_column(String(32))
  tags_json: Mapped[list[str] | None] = mapped_column(JSON, default=list)
  ai_summary: Mapped[str | None] = mapped_column(Text)
  visibility: Mapped[str] = mapped_column(Enum("private", "shared", "partner_only", name="diary_visibility"), default="shared")

  user: Mapped["User"] = sa_relationship(back_populates="diary_entries", lazy="joined")
  relationship: Mapped["Relationship | None"] = sa_relationship("Relationship", lazy="joined")
  comments: Mapped[list["DiaryComment"]] = sa_relationship(
    "DiaryComment", back_populates="diary_entry", cascade="all, delete-orphan", lazy="select"
  )
